/*
 * @Auther: Ye Chen
 * @Date: 2020-07-29 14:18:16
 * @LastEditors: Ye Chen
 * @LastEditTime: 2020-07-31 11:25:46
 * @Description:
 */
// import Vue from 'vue'
import axios from 'axios'
import router from '@/router'
import { Notification } from 'element-ui'
import { VueAxios } from './axios'

// 创建 axios 实例
const service = axios.create({
  baseURL: process.env.VUE_APP_API_BASE_URL, // api base_url
  timeout: 30000 // 请求超时时间
})

const err = error => {
  if (error.response) {
    if (error.response.status === 403) {
      Notification.error({
        title: '错误',
        message: '没有访问权限'
      })
    }
    if (error.response.status === 401) {
      console.log(router)
      Notification.error({
        title: '错误',
        message: '登录过期，请重新登录'
      })
      localStorage.removeItem('ACCESS_TOKEN')
      router.push('/login')
    }
  }
  // if (error.message.includes('timeout')) {
  //   message.error('请求超时，请刷新重试')
  // }
  return Promise.reject(error)
}

// request interceptor
service.interceptors.request.use(config => {
  const token = localStorage.getItem('ACCESS_TOKEN')
  if (token) {
    config.headers['token'] = token // 让每个请求携带自定义 token 请根据实际情况自行修改
  }
  return config
}, err)

// response interceptor
service.interceptors.response.use(response => {
  // if (typeof response.data === 'object' && response.data.code === 401) {
  //   localStorage.removeItem('ACCESS_TOKEN')
  //   router.$router.push('/login')
  // }
  return response.data
}, err)

const installer = {
  vm: {},
  install(Vue) {
    Vue.use(VueAxios, service)
  }
}

export { installer as VueAxios, service as axios }
